const http = require('http');
const path = require('path');
var fs = require('fs');
// 请求2次的原因 是网络访问的2次,一次请求,一次favicon.ico
let server = http.createServer();
// mime的对象类型
const mimeTypes = {
  '.css': 'text/css',
  '.gif': 'image/gif',
  '.html': 'text/html',
  '.ico': 'image/x-icon',
  '.jpeg': 'image/jpeg',
  '.jpg': 'image/jpeg',
  '.js': 'text/javascript',
  '.json': 'application/json',
  '.pdf': 'application/pdf',
  '.png': 'image/png',
  '.svg': 'image/svg+xml',
  '.swf': 'application/x-shockwave-flash',
  '.tiff': 'image/tiff',
  '.txt': 'text/plain',
  '.wav': 'audio/x-wav',
  '.wma': 'audio/x-ms-wma',
  '.wmv': 'video/x-ms-wmv',
  '.xml': 'text/xml'
};

server.on("request", (req, res) => {
  let ext = path.extname(req.url);
  res.writeHead(200, { 'Content-Type':mimeTypes[ext] });
  fs.readFile(`./public/${req.url}`, 'binary', (err, file) => {
    if (err) {
      throw new Error(err);
    } else {
      res.write(file, 'binary');
      res.end();
    }
  });
})

server.listen("8080", () => {
  console.log("创建了项目,监听8080,访问http:127.0.0.1:8080");
})
